#include "comparator.h"
#include "io430x22x4.h"
#include "intrinsics.h"

static pf_t registred_callback_fn;

//-------------------------------------
// Comparator initialization
//-------------------------------------
void comparator_init(pf_t callback_fn){
  // register callback function
  registred_callback_fn = callback_fn;
  // -- Comparator
  // OA0CTL0 Comparator 0 control register
  OA0CTL0 |= OAADC0;   // OAADC0=01: OA0OUT connected to pin 8
  OA0CTL0 |= (OAPM0 + OAPM1); // Enable output with fast slew rate
  // OA0CTL0 Comparator 0 control register
  OA0CTL1 |= (OAFBR1 + OAFBR0);  // OAFBRx=011: 10R/6R = 0.6 with OARRIP=0
  OA0CTL1 |= (OAFC1 + OAFC0); //OAFCx=011 comparator

  // --- Vref setup
  // ADC10CTL0 ADC control register 0 
  ADC10CTL0 |= REFOUT;   // VREF externally on pin VREF+.
  ADC10CTL0 &= ~REF2_5V; // Vref = 1.5V
  ADC10CTL0 |= REFON;    // Internar Ref ON 

  //--- Pin configuration
  P2SEL |= P2SEL_4;  // P2.4 used by periferic (Vref out)
  P2SEL |= P2SEL_0;  // P2.0 used by periferic (comp in)
  P4SEL |= P4SEL_3;  // P4.3 used by periferic (comp out)

  //--- I/O interrupt
  P2DIR &= ~P2DIR_1; // P2.1 input
  P2IES &= ~P2IES_1; // interrupt when LOW to HIGH 
  P2IE  |= P2IE_1;   // Interrupt enable
    return; 
} 


void test_callback(void){
    P1OUT ^= 0x01;           // Toggle P1.0 (led)
}

#pragma vector=PORT2_VECTOR   
__interrupt void comparator_isr (void){ 
    P2IFG &= ~P2IFG_1;
    registred_callback_fn();           // Execute registered callback function;
    }
